package com.hpin.fansea.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.hpin.fansea.R;
import com.hpin.fansea.adapter.BannerAdapter;
import com.hpin.fansea.adapter.HomeModuleAdapter;
import com.hpin.fansea.adapter.SurroundListAdapter;
import com.hpin.fansea.base.BaseFragment;
import com.hpin.fansea.bean.BannerResult;
import com.hpin.fansea.bean.HomeResultBean;
import com.hpin.fansea.bean.SurroundBussniseList;
import com.hpin.fansea.home.CommunityBroadcastActivity;
import com.hpin.fansea.home.ComplaintActivity;
import com.hpin.fansea.home.GuideWorkActivity;
import com.hpin.fansea.home.PaymentActivity;
import com.hpin.fansea.home.RepairActivity;
import com.hpin.fansea.home.WaitActivity;
import com.hpin.fansea.service.SurroundActivity;
import com.hpin.fansea.service.SurroundListActivity;
import com.hpin.fansea.utils.Constant;
import com.hpin.fansea.utils.HttpUtil;
import com.hpin.fansea.utils.LogUtil;
import com.hpin.fansea.widget.GridViewForScrollView;
import com.lidroid.xutils.http.RequestParams;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

/**
 * 首页fragment
 * Created by Aaron on 2015/7/15.
 */
public class HomePageFragment extends BaseFragment implements View.OnClickListener {

    private Intent mIntent;
    private List<BannerResult.BannerDetail> bannerLists = new ArrayList<BannerResult.BannerDetail>();
    private BannerAdapter mAdapter;
    private ViewPager vp_homepage;
    private TextView tv_broadcast;
    private TextView tv_house_price;
    private ListView lv_today_recommend;
    private TextView tv_total_group;
    private SurroundListAdapter listAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LogUtil.e("TAG", "homepagefragment=====onCreate");

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_home_page, null);

//        LogUtil.e("TAG", "==========onCreateView=========");

        initWidget(view);

        // 加载轮播图
        getBunnerFromNet();

        getHomeData();

        return view;
    }

    private List<SurroundBussniseList> surroundBussniseLists = new ArrayList<>();

    private void initWidget(View view) {

        lv_today_recommend = (ListView) view.findViewById(R.id.lv_today_recommend);


        View head = View.inflate(getActivity(), R.layout.head_home_page, null);

        lv_today_recommend.addHeaderView(head);

        listAdapter = new SurroundListAdapter(getActivity(), surroundBussniseLists);
        lv_today_recommend.setAdapter(listAdapter);

        GridViewForScrollView gv_module = (GridViewForScrollView) head.findViewById(R.id.gv_module);

        tv_broadcast = (TextView) head.findViewById(R.id.tv_broadcast);
        tv_house_price = (TextView) head.findViewById(R.id.tv_house_price);

        vp_homepage = (ViewPager) head.findViewById(R.id.vp_homepage);

        tv_total_group = (TextView) head.findViewById(R.id.tv_total_group);

        RelativeLayout rl_today_recommend = (RelativeLayout) head.findViewById(R.id.rl_today_recommend);

        RelativeLayout rl_broadcast = (RelativeLayout) head.findViewById(R.id.rl_broadcast);


        rl_broadcast.setOnClickListener(this);
        rl_today_recommend.setOnClickListener(this);

        HomeModuleAdapter homeModuleAdapter = new HomeModuleAdapter(getActivity());
        gv_module.setAdapter(homeModuleAdapter);

        gv_module.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                switch (position) {

                    case 0:        //报修
                        mIntent = new Intent(getActivity(), RepairActivity.class);
                        startActivity(mIntent);

                        break;
                    case 1:// 物业缴费

                        //认证和认证通过用户
                        if (Constant.AUTH_USER.equals(sp.getString(Constant.status, ""))
                                || Constant.AUTH_PASSED.equals(sp.getString(Constant.status, ""))) {
                            //认证 和 认证通过用户
                        mIntent = new Intent(getActivity(), PaymentActivity.class);
                        startActivity(mIntent);

                        } else {
//                            showToast("认证用户才可以缴费");
                            remindAuth("提示");
                        }

                        break;
                    case 2:          //泛海航程会

                        mIntent = new Intent(getActivity(), WaitActivity.class);
                        startActivity(mIntent);
                        break;
                    case 3:         //办事指南

                        mIntent = new Intent(getActivity(), GuideWorkActivity.class);
                        startActivity(mIntent);

                        break;
                    case 4:        //周边商家

                        mIntent = new Intent(getActivity(), SurroundActivity.class);
                        startActivity(mIntent);
                        break;
                    case 5:        //联系我们

                        mIntent = new Intent(getActivity(), ComplaintActivity.class);
                        startActivity(mIntent);
                        break;

                }

            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();

        MobclickAgent.onPageStart(getClass().getName()); //统计页面
////        LogUtil.e("TAG", "=====onResume====");
//        pageNum = 1;
//
//        msgBeanList.clear();
//
//        loadRefushData();

    }

    /**
     * 获取轮播图
     */
    private void getBunnerFromNet() {

        RequestParams params = new RequestParams();

        params.addQueryStringParameter("systemType", Constant.SYSTEM_TYPE);
        params.addQueryStringParameter("location", Constant.HOMEPAGER);
        params.addQueryStringParameter("projectId", sp.getString(Constant.communityId, ""));

        HttpUtil.getInstance().setGetRequest("加载中...", getActivity(), Constant.WEB_ROOT + Constant.GETBUNNER, params, new HttpUtil.SuccessListener() {
            @Override
            public void setOnSuccessListener(String str) {

                try {

                    BannerResult bannerResult = JSONObject.parseObject(str, BannerResult.class);

                    if (Constant.STATUS_SUCESS.equals(bannerResult.status)) {

                        bannerLists = bannerResult.result;

                        mAdapter = new BannerAdapter(bannerLists, getActivity());
                        vp_homepage.setAdapter(mAdapter);

                        //开始轮播
                        startPlay();

                    } else {
                        showToast(bannerResult.message);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }, null);

    }

    /**
     * 获取首页数据
     */
    private void getHomeData() {

        HttpUtil.getInstance().setGetRequest("获取中...", getActivity(), Constant.WEB_ROOT + Constant.HOMEDATA
                + "?token=" + sp.getString(Constant.token, "") + "&systemType=" + Constant.SYSTEM_TYPE + "&dictId=" + Constant.RECOMMEND
                + "&communityId=" + sp.getString(Constant.communityId, "") + "&pageSize=10&pageIndex=1"
                , new HttpUtil.SuccessListener() {

            @Override
            public void setOnSuccessListener(String str) {

                try {

                    HomeResultBean homeResultBean = JSONObject.parseObject(str, HomeResultBean.class);

                    if (Constant.STATUS_SUCESS.equals(homeResultBean.status)) {

                        //广播
                        tv_broadcast.setText(homeResultBean.result.cellBroadcast.cbName);

                        tv_house_price.setText("房屋均价:   " + homeResultBean.result.housePrice + "元/平米");

                        tv_total_group.setText("共" + homeResultBean.result.nearBussniseCount + "家");

//                        List<SurroundBussniseList> nearBussniseVoList = homeResultBean.result.nearBussniseVoList;
//
//                        SurroundListAdapter surroundAdapter = new SurroundListAdapter(getActivity(), nearBussniseVoList);
//
//                        lv_today_recommend.setAdapter(surroundAdapter);
                        listAdapter.setData(homeResultBean.result.nearBussniseVoList);
                        listAdapter.notifyDataSetChanged();

                    } else {
                        showToast(homeResultBean.message);
                    }

                } catch (Exception e) {
                    showToast("获取数据失败");
                    e.printStackTrace();
                }

            }
        }, null);

    }

    private boolean actionNotDown = true;
    private static final int CHANGEPIC = 004;

    /**
     * 开始轮播
     */
    private void startPlay() {

        //设置无限轮播的起点
        if (bannerLists == null || bannerLists.size() == 0)
            return;

        int middle = Constant.MAX_SIZE / 2;

        int firstItem = (middle / bannerLists.size()) * bannerLists.size();

        LogUtil.e("tag", "firstItem===" + firstItem);

        vp_homepage.setCurrentItem((middle / bannerLists.size()) * bannerLists.size());

        vp_homepage.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            /**
             * 当页面选择发生改变的时候，
             * position 新页面的下标
             */
            public void onPageSelected(int position) {

            }

            @Override
            /**
             * 当页面滑动时的回调监听
             */
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                currentPosition = position;
            }

            @Override
            /**
             * 当页面的滑动状态发生改变的时候，
             * 如：手指按下状诚，滑动状态，抬起状态
             */
            public void onPageScrollStateChanged(int state) {
            }
        });

        vp_homepage.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                actionNotDown = false;
                return false;
            }
        });

        // 让轮播图滚动
        if (isStop) {
            startRoll();
            isStop = false;
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

        isStop = false;
    }

    /**
     * 让轮播图滚动
     */
    public void startRoll() {

        new Thread(new Runnable() {

            @Override
            public void run() {
                SystemClock.sleep(Constant.MSG_DELAY);
                handler.sendEmptyMessage(CHANGEPIC);
            }
        }).start();

    }

    private int currentPosition;
    private int item;
    private boolean isStop = true;

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case CHANGEPIC:

                    if (actionNotDown) {

                        //做判断 以防万一
                        if (bannerLists == null || bannerLists.size() == 0 || bannerLists.size() == 1)
                            return;

                        item = (currentPosition++) % (bannerLists.size());
                        vp_homepage.setCurrentItem(item, false);
                    } else {
                        actionNotDown = true;
                    }
                    startRoll();
                    break;
                default:
                    break;
            }

        }
    };

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(getClass().getName());
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.rl_broadcast://小区广播

                Intent mIntent = new Intent(getActivity(), CommunityBroadcastActivity.class);
                startActivity(mIntent);

                break;

            case R.id.rl_today_recommend:

                mIntent = new Intent(getActivity(), SurroundListActivity.class);
                mIntent.putExtra("type", Constant.RECOMMEND);
                mIntent.putExtra("title", getResources().getString(R.string.surround_recommend));
                startActivity(mIntent);
                break;

        }

    }


//    /**
//     * 如果有更多则进行重复判断
//     *
//     * @param temp
//     *            新的集合
//     */
//    protected void setDataView(List<MessageReceive.MsgBean> temp) {
//
//        if (msgBeanList.size()==0) {
//            msgBeanList = temp;
//            return;
//        }
//
//        int nowSize = msgBeanList.size();
//        int newSize = temp.size();
//        for (int i = 0; i < newSize; i++) {
//            boolean exist = true;
//            MessageReceive.MsgBean mcod = temp.get(i);
//            for (int j = 0; j < nowSize; j++) {
//                MessageReceive.MsgBean nmcod = msgBeanList.get(j);
//                if (mcod.id.equals(nmcod.id)) {
//                    exist = false;
//                    break;
//                }
//            }
//            if (exist)
//                msgBeanList.add(mcod);
//
//        }
//    }

}
